package com.scalar.chiptrack.operations.dataentry.lotTransfer.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.dataentry.lotTransfer.forms.TransferMaterialForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.reports.dao.DataDumpReportsDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.utils.StringUtils;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 19 May, 2010
 * Time: 3:04:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class TransferMaterialReportCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/transferMaterial.do";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {

        TransferMaterialForm transferMaterialForm = (TransferMaterialForm) form;

        HashMap<String, String> errors  = new HashMap<String, String>();
        HashMap<String, String> info    = new HashMap<String, String>();
        String action = request.getParameter("action");

        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(ERROR_MESSAGES, errors);

        HttpSession mSession = request.getSession();
        User user = (User) mSession.getAttribute(SessionKeys.USER_KEY);
        ArrayList lotInfoList = null;
        Workbook workbook = null;
        String fileName = "";
        if (user == null)
        {
            mSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
            return (mapping.findForward("login"));
        }
        else
        {
            if (user.isActionAllowed(Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY))
            {
                request.setAttribute("showMessage", "FALSE");
            }
            else
            {
                request.setAttribute("showMessage", "TRUE");
            }
        }

        try
        {
            if ( "transferMaterialReport".equalsIgnoreCase(action))
            {
                if ( transferMaterialForm.getProcessType() == null || "0".equalsIgnoreCase(transferMaterialForm.getProcessType()))
                {
                      request.setAttribute( "partNumberList", new ArrayList() );
                      request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, "ALL") );
                }
                else
                {
                    if ( transferMaterialForm.getBaseProductId() > 0 )
                    {
                        request.setAttribute( "partNumberList", ProductDao.getPartNumberByBaseProductAndPsTypeList(transferMaterialForm.getProcessType() , transferMaterialForm.getBaseProductId() ) );
                    }
                    else
                    {
                        request.setAttribute( "partNumberList", ProductDao.loadAllPartsForProcessTypeByPsType( transferMaterialForm.getProcessType() ) );
                    }
                    request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, transferMaterialForm.getProcessType() ));
                }
                //request.setAttribute("deptList", LotDetails.getDepartmentsList() );
                request.setAttribute( "processTypeList",  NewProductDAO.loadAllProcessesFromDB(null, false) );
                request.setAttribute( "baseProductList", ProductDao.loadChipBaseProducts(null) );

                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MONTH, -1);
                cal.set(Calendar.DAY_OF_MONTH, 1);
                transferMaterialForm.setFromDate( DateUtil.formatDate( cal.getTime(),  "MM/dd/yyyy" ) );
	            transferMaterialForm.setToDate( DateUtil.getCurrentDate() );
            }
            else if ("transferMaterialReportExcel".equalsIgnoreCase(action) )
            {
                String vendorNames      = request.getParameter( "prompt0" );
                String processType      = transferMaterialForm.getProcessType();
                String processstepIds   = transferMaterialForm.getProcessStepId()+"";
                String baseProductIds   = transferMaterialForm.getBaseProductId()+"";
                String fromDate   = transferMaterialForm.getFromDate();
                String toDate   = transferMaterialForm.getToDate();

                fileName = "Transfer Material Report From "+StringUtils.formatDate(fromDate, "MM/dd/yyyy", "dd-MMM-yyyy" ) + " To " +StringUtils.formatDate(toDate, "MM/dd/yyyy", "dd-MMM-yyyy" ) +"_"+ DateUtil.getTimeStamp() ;

                lotInfoList = DataDumpReportsDAO.getTransferMaterialReport ( null, processType, processstepIds, baseProductIds, vendorNames, fromDate, toDate);

                workbook =  DataDumpReportsHelper.getWorkbook(lotInfoList, "Transfer Material Report",  fromDate, toDate, null );

                 ExcelUtils.generateExcelReport( workbook, fileName, response );
            }
       }
       catch( Exception e)
       {

          errors.put( "Could not Get Transfer Materail Receive Report details", null);
          e.printStackTrace();
       }

        return mapping.findForward("transferMaterialReport");
    }

}
